package org.bird.concurrent;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 
 * @author liangjf
 *
 */
public class ArrayBlockingQueueDemo {

	private static BlockingQueue<String> queue = new ArrayBlockingQueue<String>(10);

	public static void main(String[] args) throws InterruptedException {
		ArrayBlockingQueueDemo demo = new ArrayBlockingQueueDemo();
		Producer producer1 = demo.new Producer("生产者001");
		Producer producer2 = demo.new Producer("生产者002");
		Consumer consumer = demo.new Consumer("消费者001");
		ExecutorService service = Executors.newCachedThreadPool();
		
		service.submit(producer2);
		service.submit(producer1);
		service.submit(consumer);
		// 执行10s
		Thread.sleep(10 * 1000);
		producer1.stop();
		producer2.stop();
		
		// 退出Executor
        service.shutdown();
	}

	class Producer implements Runnable {
		private String instance;
		private int i = 1;
		private volatile boolean isRunning = true;
		
		public Producer(String instance) {
			this.instance = instance;
		}
		
		@Override
		public void run() {
			while (isRunning) {
				System.out.println(instance + "生产了第" + i + "苹果");
				try {
					queue.put(instance + "生产的第" + i++ + "苹果");
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

		}
		
		public void stop() {
			isRunning = false;
		}
	}

	class Consumer implements Runnable {

		private String instance;
		private volatile boolean isRunning = true;
		
		public Consumer(String instance) {
			this.instance = instance;
		}
		
		@Override
		public void run() {
			while (isRunning) {
				try {
					System.out.println(instance + "消费了" + queue.take());
					 Thread.sleep(1500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		
		public void stop() {
			isRunning = false;
		}
	}
}
